package com.cq.xjms.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.extremecomponents.table.limit.Limit;

import com.cq.xjms.model.Student;
import com.cq.xjms.model.Teacher;
import com.cq.xjms.model.User;
import com.cq.xjms.service.SysManager;
/**
 * 系统管理
 * @author caiqiang
 * @version 1
 */
public class SysManagerImpl extends BaseManagerImpl implements SysManager{
	private static Logger LOG = Logger.getLogger(SysManagerImpl.class);
	private static final int STUDENT_LOGIN = 3;
	private static final int TEACHER_LOGIN =2 ;
	private static final int ADMIN_LOGIN = 1;
	@Override
	public Object login(String userNo, String password,int loginType) {
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("userNo", userNo);
		param.put("password", password);
		String query = null;
		if(ADMIN_LOGIN == loginType){
			query = User.USER_LOGIN;
		}else if(TEACHER_LOGIN == loginType){
			query = Teacher.TEACHER_LOGIN;
		}else if(STUDENT_LOGIN == loginType){
			query = Student.STUDENT_LOGIN;
		}
		List users = this.find(query,param);
		if(users!=null&&users.size()>0)
			return users.get(0);
		return null;
	}
	@Override
	public List<User> queryUsers(Map<String, Object> params,Limit limit) {
		String hql = generateHql(params);
		LOG.info(hql);
		List<User> users = null;
		try{
			users = this.findByHQL(hql, null, limit);
		}catch(Exception e){
			LOG.error("query user", e);
		}
		return users;
	}
	
	

	@Override
	public int countUsers(Map<String, Object> params) {
		return this.countByHQL(generateHqlByCount(params), null);
	}

	private String generateHql(Map<String, Object> map) {
		StringBuffer hql = new StringBuffer();
		hql.append("select u from User u ");
		if (map.size() > 0) {
			hql.append(" where 1=1 ");
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				hql.append(" and u." + key + "=" + map.get(key));
			}
		}
		hql.append(" order by u.createDate desc");
		return hql.toString();
	}
	private String generateHqlByCount(Map<String, Object> map) {
		StringBuffer hql = new StringBuffer();
		hql.append("select count(u) from User u ");
		if (map.size() > 0) {
			hql.append(" where 1=1 ");
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				hql.append(" and u." + key + "=" + map.get(key));
			}
		}
		return hql.toString();
	}

}
